package com.taoyun.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taoyun.mapper.FileMapper;
import com.taoyun.mapper.UserMapper;
import com.taoyun.pojo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;

/**
 *  用户相关工具类
 * @author FengJingdong
 */
@Component
public class UserUtil {
    private static JedisPool jedisPool;
    private static UserMapper userMapper;
    private static FileMapper fileMapper;

    private static final int RENEW_TIME = 1800;

    @Autowired
    public UserUtil(JedisPool jedisPool,UserMapper userMapper,FileMapper fileMapper) {
        UserUtil.jedisPool = jedisPool;
        UserUtil.userMapper = userMapper;
        UserUtil.fileMapper = fileMapper;
    }

    /**
     *  通过 HttpServletRequest 获取当前访问对象
     *
     * @param request 前端 header tokenLogin 字段
     * @return User 当前访问对象
     */
    public static User getUserByRequest(HttpServletRequest request){
        // 获取头部的令牌
        String tokenLogin = request.getHeader("tokenLogin");
        User user;
        try(Jedis jedis = jedisPool.getResource()){
            // redis读token，转换成User对象
            String jsonRst = jedis.get(tokenLogin);
            ObjectMapper mapper = new ObjectMapper();
            user = mapper.readValue(jsonRst, User.class);
            // 重新设置键值对的有效时间
            jedis.expire(tokenLogin, RENEW_TIME);
            return user;
        }catch (JsonProcessingException jpe ){
            throw new RuntimeException("redis 数据解析异常");
        }catch (Exception e){
            throw new RuntimeException("Jedis 客户端连接异常/头部没有tokenLogin");
        }
    }

    /**
     * 查询用户可以删除文件
     *
     * @param user 当前用户
     * @param fileId 删除的文件
     * @return 是否可以删除
     */
    public static boolean hasDeletePermission(User user,Integer fileId) {
        if(user == null || user.getUserId()==null || fileId == null){
            return false;
        }
        // 查询是否有User-file删除权限
        boolean userFile  = fileMapper.checkRelateByUserIdAndFileId(user.getUserId(),fileId)>0;
        if(userFile){
            return true;
        }else {
            // 查询是否有组删除权限
            boolean groupFile = fileMapper.checkRelateGroup(user.getUserId(),fileId)>0;
            // 判断是否是管理员
            if(!groupFile){
                return "超管".equals(user.getPermission()) || "管理员".equals(user.getPermission()) ;
            }
            return true;
        }

    }
}
